package com.ibeeking.found.workflow.b.rest.config.listener;

import com.ibeeking.found.common.entity.CurrentUser;
import com.ibeeking.found.workflow.b.rest.service.FlowWorkOrderService;

import com.ibeeking.found.workflow.b.rest.config.FlowCustomExtFactory;
import com.ibeeking.found.workflow.service.common.constants.FlowTaskStatus;
import com.ibeeking.found.workflow.service.common.dos.FlowWorkOrder;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.utils.data.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;

/**
 * 流程实例监听器，在流程实例结束的时候，需要完成一些自定义的业务行为。如：
 * 1. 更新流程工单表的审批状态字段。
 * 2. 业务数据同步。
 *
 * @author Jerry
 * @date 2021-06-06
 */
@Slf4j
public class FlowFinishedListener implements ExecutionListener {

    private final FlowWorkOrderService flowWorkOrderService = SpringBeanUtil.getBean(FlowWorkOrderService.class);
    private final FlowCustomExtFactory flowCustomExtFactory = SpringBeanUtil.getBean(FlowCustomExtFactory.class);

    @Override
    public void notify(DelegateExecution execution) {
        if (!StringUtils.equals("end", execution.getEventName())) {
            return;
        }
        String processInstanceId = execution.getProcessInstanceId();
        flowWorkOrderService.updateFlowStatusByProcessInstanceId(processInstanceId, FlowTaskStatus.FINISHED);
        String businessKey = execution.getProcessInstanceBusinessKey();
        FlowWorkOrder workOrder = flowWorkOrderService.getFlowWorkOrderByProcessInstanceId(processInstanceId);
        flowCustomExtFactory.getBusinessDataExtHelper()
                .triggerSync(workOrder.getProcessDefinitionKey(), processInstanceId, businessKey);
    }
}
